import cgi,os,re,datetime,copy
from django.utils import simplejson

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.ext.webapp import template

class Greeting(db.Expando):
    author = db.StringProperty()
    content = db.StringProperty(multiline=True)
    date = db.DateTimeProperty()
    score_tq = db.IntegerProperty(default=0)
    score_jd = db.IntegerProperty(default=0)

class MainPage(webapp.RequestHandler):
    def get(self):
	pn = self.request.get('page_num').strip()

	if pn:
		pn = int(pn)
	else:
		pn = 20

        greetings_query = Greeting.all().order('-date')
        greetings = greetings_query.fetch(pn)

        for i in greetings:
            i.id = str(i.key().id())

        template_values = {
            'greetings': greetings,
            }

        path = os.path.join(os.path.dirname(__file__), 'index.html')
        self.response.out.write(template.render(path, template_values))

class Guestbook(webapp.RequestHandler):
    def post(self):
        greeting = Greeting()

	m=re.compile(r'\[img\](?!\[img\])(\S+?)\[\/img\]',re.IGNORECASE)
	v=re.compile(r'\[video\](?!\[video\])(\S+?)\[\/video\]',re.IGNORECASE)

	greeting.author = self.request.get('name').strip()
        greeting.content = self.request.get('content')

	if self.synaxCheck(greeting.author) and self.synaxCheck(greeting.content):
            img_urls = list(set(m.findall(greeting.content)))
            video_urls = list(set(v.findall(greeting.content)))
            
            #adjust image tag
            for url in img_urls:
                t = re.compile(url)
                greeting.content = t.sub('<img src="'+url+'"/>',greeting.content)
            for url in video_urls:
                t = re.compile(url)
                greeting.content = t.sub('<embed src="'+url+'" quality="high" width="480" height="400" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash"></embed>',greeting.content)
            
            greeting.content = greeting.content.replace(r'[img]','').replace(r'[/img]','')
            greeting.content = greeting.content.replace(r'[video]','').replace(r'[/video]','')
            greeting.date = datetime.datetime.now() + datetime.timedelta(hours=8)
            greeting.score_tq = 0
            greeting.score_jd = 0
            
            greeting.put()
        self.redirect('/')

    def synaxCheck(self,str):
	js=re.compile(r'.*?\<.*?(script|iframe|div).*?\>',re.IGNORECASE)
	r=re.compile(r'.*?\<.*?(javascript:)|(o.*n.+?=.+?).*?\>',re.IGNORECASE)
	
	if str != '':
		if js.search(str) or r.search(str):
			return False
		else:
			return True
	else:
		return True

class Content(webapp.RequestHandler):
    def get(self):
	self.__fetchContent()

    def post(self):
        self.__fetchContent()

    def __fetchContent(self):
	data = {}
        tmp = {}
        llist = []
        start_pos = self.request.get('start')
        end_pos = self.request.get('len')

	if start_pos:
            start_pos = int(start_pos)

        if end_pos:
            end_pos = int(end_pos)
        
        greetings_query = Greeting.all().order('-date') 
	contents = greetings_query.fetch(end_pos,offset=start_pos)

	if contents:
            data['status'] = 'ok'
            for content in contents:
                tmp.clear()
                tmp['author'] = content.author
                tmp['content'] = content.content
                tmp['date'] = content.date.strftime("%b-%d %H:%M:%S")
              
                llist.append(copy.deepcopy(tmp))
            data['data'] = llist
	else:
            data['status'] = 'error'
            data['data'] = ''

        self.response.out.write(simplejson.dumps(data))	

application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/sign', Guestbook),
                                      ('/content', Content)],
                                    debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
